package com.wang.leetcode;

/**
 * @Author: along
 * @Create: 2021/4/14 10:26
 * @Description:合并两个有序链表，递归，迭代
 */
public class Sword25 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
    //递归
    public ListNode mergeTwoList(ListNode l1, ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }
        if(l1.val <= l2.val) {
            l1.next = mergeTwoList(l1.next, l2);
            return l1;
        }
        else {
            l2.next = mergeTwoList(l2.next, l1);
            return l2;
        }
    }
    //迭代
    //定义一个虚头，所以就不需要考虑l1，l2谁是头节点了
    public ListNode mergeTwoList2(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(-1);
        ListNode pre = dummyHead;
        while (l1 != null && l2 != null) {
            if(l1.val <= l2.val) {
                pre.next = l1;
                pre = pre.next;
                l1 = l1.next;
            }
            else {
                pre.next = l2;
                pre = pre.next;
                l2 = l2.next;
            }
        }
        if(l1 == null) {
            pre .next = l2;
        }
        if(l2 == null) {
            pre.next = l1;
        }
        return dummyHead.next;
    }
}
